//
//  GameManager.swift
//  If Light
//
//  Created by 姬向阳 on 2020/5/3.
//  Copyright © 2020 SUNNYJ. All rights reserved.
//

import SwiftUI
import Combine

// MARK:- Model

struct Light {
    var status: Bool = Bool.random()
}

class GameManager : ObservableObject{
    @Published var gameStatus: GameStatus = .ready {
        didSet {
            switch gameStatus {
            case .finish:
                timer.cancelTimer()
            case .play:
                timer.startTimer { timeString in
                    self.timeString = timeString
                }
            case .ready:
                break
            }
        }
    }
    
    var timer = Timer.shared
    
    @Published var timeString = "00:00:00"
    
    @Published var clickTimes = 0
    
    @Published var lights = [
        [Light(),Light(),Light()],
        [Light(),Light(),Light()],
        [Light(),Light(),Light()]
    ]

    /// 通过坐标索引修改灯状态
    /// - Parameters:
    ///   - row: 行索引  0至lights.count-1
    ///   - index: 列索引 0至lights[row].count-1
    func updateLightStatus(row: Int ,index: Int) {
        
        lights[row][index].status.toggle()
        
        if gameStatus == .ready {
            gameStatus = .play
        }
        
        // 上
        let top = row - 1
        if !(top < 0) {
            lights[top][index].status.toggle()
        }
        // 下
        let bottom = row + 1
        if !(bottom > lights.count - 1) {
            lights[bottom][index].status.toggle()
        }
        // 左
        let left = index - 1
        if !(left < 0) {
            lights[row][left].status.toggle()
        }
        // 右
        let right = index + 1
        if !(right > lights[row].count - 1) {
            lights[row][right].status.toggle()
        }
        
        if gameStatus == .play {
            clickTimes += 1
            updateGameStatus()
        }
    }
    
    /// 判胜
    private func updateGameStatus() {
        var lightConut = 0
        
        for lightArr in lights {
            for light in lightArr {
                if light.status { lightConut += 1 }
            }
        }
        
        if lightConut == 0 {
            gameStatus = .finish
        }
    }
    
    /// 重新开始游戏
    func restartGame() {
        resetLights()
        clickTimes = 0
        gameStatus = .ready
    }
    
    /// 重置所有灯
    private func resetLights() {
        lights = [
            [Light(),Light(),Light()],
            [Light(),Light(),Light()],
            [Light(),Light(),Light()]
        ]
    }
}

// MARK:- extension

extension GameManager {
    enum GameStatus {
        case ready
        case play
        case finish
    }
}


